package com.demomaster.quickcompat.widget.dialog;

import static android.view.View.GONE;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.annotation.IntDef;
import androidx.appcompat.app.AppCompatDialog;
import androidx.core.view.ScrollingView;

import com.demomaster.quickcompat.R;
import com.demomaster.quickcompat.widget.base.QuickGravity;
import com.demomaster.quickcompat.widget.slidingpanellayout.SlidingUpPanelLayout;

import java.io.Serializable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;


/**
 * Created by Squirrel桓
 */
public class QuickDialog extends AppCompatDialog {

    public int width = ViewGroup.LayoutParams.MATCH_PARENT;
    public int height = ViewGroup.LayoutParams.MATCH_PARENT;
    public int gravity = QuickGravity.CENTER.value();
    public boolean canSliding;//是否可以滑动
    public boolean enablePadding;//是否启用padding
    public boolean canceledOnTouchOutside = true;
    public boolean isFullScreen = false;
    public int margin = 0;//当isFullScreen=true时生效
    public int contentViewLayoutID = Resources.ID_NULL;
    public int animationStyleID;
    private String TAG = "QuickDialog";

    public QuickDialog(Context context) {
        super(context);
        init(null);
    }

    public QuickDialog(Context context, int themeResId) {
        super(context, themeResId);
        init(null);
    }

    public QuickDialog(Context context, int themeResId, Builder builder) {
        super(context, themeResId);
        init(builder);
    }

    View contentLayout;
    public QuickDialog(Context context, Builder builder) {
        super(context);
        //this.builder = builder;
        width = builder.width;
        height = builder.height;
        contentLayout = builder.contentView;
        contentViewLayoutID = builder.layoutResID;
        animationStyleID = builder.animationStyleID;
        //this.bindViewsMap = builder.bindViewsMap;
        isFullScreen = builder.isFullScreen;
        canSliding = builder.canSliding;
        enablePadding = builder.enablePadding;
        margin = builder.margin;
        gravity = builder.quickGravity == null ? QuickGravity.CENTER.value() : builder.quickGravity.value();
        setCancelable(builder.cancelable);
        init(builder);
    }

    int paddingLeft0;
    int paddingTop0;
    int paddingRight0;
    int paddingBottom0;

    public void init(Builder builder) {
        Window win = getWindow();
        paddingLeft0 = win.getDecorView().getPaddingLeft(); // 获取左边距
        paddingTop0 = win.getDecorView().getPaddingTop(); // 获取上边距
        paddingRight0 = win.getDecorView().getPaddingRight(); // 获取右边距
        paddingBottom0 = win.getDecorView().getPaddingBottom(); // 获取下边距

        if (isFullScreen) {//全屏显示
            win.setType(WindowManager.LayoutParams.TYPE_APPLICATION_PANEL);
            win.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            win.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        }
        getWindow().setGravity(gravity);

        win.setWindowAnimations(animationStyleID);
        win.setBackgroundDrawableResource(android.R.color.transparent);
        if (contentViewLayoutID != Resources.ID_NULL) {
            setContentView(contentViewLayoutID);
        } else if (contentLayout != null) {
            setContentView(contentLayout);
        }
        setEnablePadding(enablePadding);
        //initView();
    }

    boolean cancelable = true;

    @Override
    public void setCancelable(boolean flag) {
        cancelable = flag;
        super.setCancelable(flag);
    }

    //可滑动布局
    public boolean isCanSliding() {
        return canSliding;
    }

    SlidingUpPanelLayout slidingUpPanelLayout;//滚动布局
    SlidingUpPanelLayout.PanelSlideListener panelSlideListener;
    int panelMarginTop;//滚动布局时顶部边距

    public void setPanelMaginTop(int maginTop) {
        panelMarginTop = maginTop;
        if (slidingUpPanelLayout != null) {
            slidingUpPanelLayout.setPanelMaginTop(panelMarginTop);
        }
    }

    private View contentView;

    public View getContentView() {
        return contentView;
    }

    @Override
    public void setContentView(int layoutResID) {
        if (isCanSliding()) {
            slidingUpPanelLayout = (SlidingUpPanelLayout) getLayoutInflater().inflate(R.layout.quick_dialog_layout_sliding, null);
            slidingUpPanelLayout.setShowBackground(false);
            slidingUpPanelLayout.setPanelMaginTop(panelMarginTop);
            setScrollView(slidingUpPanelLayout, contentView);
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParams.gravity = QuickGravity.BOTTOM.value();
            super.setContentView(slidingUpPanelLayout, layoutParams);
            ViewGroup dragView = slidingUpPanelLayout.findViewById(R.id.dragView);
            getLayoutInflater().inflate(layoutResID, dragView, true);
        } else {
            super.setContentView(layoutResID);
        }

        ViewGroup rootView = findViewById(android.R.id.content);
        this.contentView = rootView.getChildAt(0);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        getWindow().setLayout(width, height);
        //this.contentView.setLayoutParams(layoutParams);
        setEnablePadding(enablePadding);
    }

    public void setEnablePadding(boolean enablePadding) {
        this.enablePadding = enablePadding;
        if (enablePadding) {
            getWindow().getDecorView().setPadding(paddingLeft0, paddingTop0, paddingRight0, paddingBottom0);
        } else {
            getWindow().getDecorView().setPadding(0, 0, 0, 0);
        }
    }

    @Override
    public void setContentView(View contentView) {
        this.contentView = contentView;
        this.contentView.setBackgroundColor(Color.GREEN);
        if (isCanSliding()) {
            slidingUpPanelLayout = (SlidingUpPanelLayout) getLayoutInflater().inflate(R.layout.quick_dialog_layout_sliding, null);
            slidingUpPanelLayout.setShowBackground(false);
            slidingUpPanelLayout.setPanelMaginTop(panelMarginTop);
            setScrollView(slidingUpPanelLayout, contentView);
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParams.gravity = QuickGravity.BOTTOM.value();
            super.setContentView(slidingUpPanelLayout, layoutParams);
            ViewGroup dragView = slidingUpPanelLayout.findViewById(R.id.dragView);
            dragView.addView(contentView, contentView.getLayoutParams());
        } else {
            super.setContentView(contentView);
        }
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        contentView = view;
        if (isCanSliding()) {
            slidingUpPanelLayout = (SlidingUpPanelLayout) getLayoutInflater().inflate(R.layout.quick_dialog_layout_sliding, null);
            slidingUpPanelLayout.setShowBackground(false);
            slidingUpPanelLayout.setPanelMaginTop(panelMarginTop);
            ViewGroup view1 = slidingUpPanelLayout.findViewById(R.id.dragView);
            view1.addView(contentView, params);
            setScrollView(slidingUpPanelLayout, contentView);
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParams.gravity = QuickGravity.BOTTOM.value();
            super.setContentView(slidingUpPanelLayout, layoutParams);
        } else {
            super.setContentView(view, params);
        }
    }

    public SlidingUpPanelLayout getSlidingUpPanelLayout() {
        return slidingUpPanelLayout;
    }

    public void setScrollView(View scrollView) {
        slidingUpPanelLayout.setScrollableView(scrollView);
    }

    public QuickDialog bindView(@IdRes int viewResId, String text) {
        View view = findViewById(viewResId);
        if (view instanceof TextView) {
            ((TextView) view).setText(text);
        }
        return this;
    }

    public QuickDialog bindView(@IdRes int viewResId, OnClickActionListener onClickListener) {
        View view = findViewById(viewResId);
        if (view != null) {
            view.setOnClickListener(v -> {
                if (onClickListener != null) {
                    onClickListener.onClick(QuickDialog.this, v, null);
                }
            });
        }
        return this;
    }

    public QuickDialog bindView(@IdRes int viewResId, String text, OnClickActionListener onClickListener) {
        View view = findViewById(viewResId);
        if (view instanceof TextView) {
            ((TextView) view).setText(text);
        }
        if (view != null) {
            view.setOnClickListener(v -> {
                if (onClickListener != null) {
                    onClickListener.onClick(QuickDialog.this, v, null);
                }
            });
        }
        return this;
    }

    @Override
    public <T extends View> T findViewById(@IdRes int id) {
        if (contentView != null) {
            View view = contentView.findViewById(id);
            if (view != null) {
                return (T) view;
            }
        }
        return getDelegate().findViewById(id);
    }

    @Override
    protected void onStart() {
        super.onStart();
        initslidingUpPanelLayout();
    }

    //初始化滚动布局
    public void initslidingUpPanelLayout() {
        if (isCanSliding() && slidingUpPanelLayout != null) {
            int h = contentView.getMeasuredHeight();
            Log.i(TAG,"h=" + h + ",panelMarginTop=" + panelMarginTop);
            slidingUpPanelLayout.setPanelMaginTop(panelMarginTop);
            slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
            (slidingUpPanelLayout).setOnClickListener(v -> {
                if (cancelable) {
                    dismiss();
                }
            });
            (slidingUpPanelLayout.findViewById(R.id.fl_bg)).setOnClickListener(v -> {
                if (cancelable) {
                    dismiss();
                }
            });
            if (panelSlideListener == null) {
                panelSlideListener = new SlidingUpPanelLayout.PanelSlideListener() {
                    @Override
                    public void onPanelSlide(View panel, float slideOffset) {

                    }

                    @Override
                    public void onPanelStateChanged(View panel, SlidingUpPanelLayout.PanelState previousState, SlidingUpPanelLayout.PanelState newState) {
                        if (newState == SlidingUpPanelLayout.PanelState.COLLAPSED) {
                            dismiss();
                        }
                    }
                };
            }
            slidingUpPanelLayout.addPanelSlideListener(panelSlideListener);
        }
    }

    /**
     * 设置scrollview
     *
     * @param container
     * @param view
     * @return
     */
    private boolean setScrollView(SlidingUpPanelLayout container, View view) {
        // container.setPanelHeight(600);
        // container.setAnchorPoint(0.7f);
        if (view instanceof ScrollingView) {
            container.setScrollableView(view);
            return true;
        } else if (view instanceof AbsListView) {
            container.setScrollableView(view);
            return true;
        }
        if (view instanceof ViewGroup) {
            int count = ((ViewGroup) view).getChildCount();
            for (int i = 0; i < count; i++) {
                boolean b = setScrollView(container, ((ViewGroup) view).getChildAt(i));
                if (b) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void setCanceledOnTouchOutside(boolean cancel) {
        canceledOnTouchOutside = cancel;
        super.setCanceledOnTouchOutside(cancel);
    }

    @Override
    public void show() {
        // 注意 这里不要使用 getContext()
        if (getContext() instanceof Activity) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                if (((Activity) getContext()).isDestroyed()) {
                    return;
                }
            }
            if (((Activity) getContext()).isFinishing()) {
                return;
            }
        } else if (getContext() instanceof ContextThemeWrapper) {

        } else {
            return;
        }
        super.show();
    }

    public enum DataType {
        radio, checkbox, text, editor
    }

    public static class Builder<T extends Builder> implements Serializable {
        public Context context;
        public int width = ViewGroup.LayoutParams.MATCH_PARENT;
        public int height = ViewGroup.LayoutParams.WRAP_CONTENT;
        public boolean isFullScreen = false;
        public boolean fullWidth;//宽度撑满
        public boolean fullHeight;//高度撑满
        public int margin = 0;//当isFullScreen=true时生效
        public View contentView;
        public int layoutResID = R.layout.quick_dialog_layout;
        public boolean cancelable = true;
        public boolean canSliding;
        public boolean enablePadding = true;//是否启用padding
        public int animationStyleID = R.style.qd_dialog_animation_center_scale;
        //public Map<Integer, ActionButton> bindViewsMap;
        public QuickGravity quickGravity;

        public Builder(Context context) {
            this.context = context;
            //bindViewsMap = new HashMap<>();
        }

        public T setCancelable(boolean cancelable) {
            this.cancelable = cancelable;
            return (T) this;
        }

        public Builder setContext(Context context) {
            this.context = context;
            return this;
        }

        public Builder setContentView(View contentView) {
            this.contentView = contentView;
            return this;
        }

        public T setContentView(int layoutResID) {
            this.layoutResID = layoutResID;
            return (T) this;
        }

        public T setAnimationStyleID(int animationStyleID) {
            this.animationStyleID = animationStyleID;
            return (T) this;
        }

        public T setCanSliding(boolean canSliding) {
            this.canSliding = canSliding;
            return (T) this;
        }

        public T setGravity(QuickGravity quickGravity) {
            this.quickGravity = quickGravity;
            return (T) this;
        }

        public T setWidth(int width) {
            this.width = width;
            return (T) this;
        }

        public Builder setFullScreen(boolean fullScreen) {
            isFullScreen = fullScreen;
            return this;
        }

        public T setEnablePadding(boolean enablePadding) {
            this.enablePadding = enablePadding;
            return (T) this;
        }

        public Builder setMargin(int margin) {
            this.margin = margin;
            return this;
        }

        public QuickDialog create() {
            return new QuickDialog(context, this);
        }
    }

    public interface OnBindViewListener {
        void onBind(Dialog dialog, View view);
    }
}
